"use client";
import { FC, PropsWithChildren, useState } from "react";
import { useRouter } from "@/i18n";
import { useSearchParams } from "next/navigation";
import HeaderBack from "@/components/HeaderBack";
import GoogleCom from "./component/GoogleCom";
import FromCom from "./component/FromCom";
import DomainFooter from "@/components/DomainFooter";
import './page.scss'
import { getLoginApi, getUserInfoApi } from "@/api/user";
import { useGlobalStore } from '@/stores';
import { Toast } from 'antd-mobile'

interface Props {}

const Login: FC<PropsWithChildren<Props>> = () => {
    const { setToken, setUserInfo } = useGlobalStore();

    const router:any = useRouter()
    let searchParams = useSearchParams();
    let redirect = searchParams.get('redirect') || ''

    const [msgError, setMsgError] = useState('')
    const loginRequest = async ({userPhone, pwd}: any) => {
        let params = {user_phone: userPhone, pwd}
        let res = await getLoginApi(params)
        if(res.code == 200) {
            setToken(res.data.token)
            getUserInfoApi().then(res1 => {
                if (res1.code == 200) {
                    Toast.show({ icon: 'success', content: '登录成功', maskClickable: false })
                    setUserInfo(res1.data)
                    setTimeout(() => {
                        router.replace('/' + redirect)
                    }, 1000)
                    
                }
            })
        }
        setMsgError(res.msg || '')
    }

    return (
        <div className="login-box">
            <HeaderBack />
            <GoogleCom />
            <FromCom callbackFun={loginRequest} msgError={msgError}/>
            <DomainFooter />
        </div>
    );
};

export default Login;
